package cn.com.callback

import groovy.json.*;

//导入grooby的json解析api包
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.EliteBean;
import cn.com.elite.PropertiesUtil;
import cn.com.elite.Util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;

/**
 * @author ThinkPad
 */

public class ecmessage implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(ecmessage.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        PropertiesUtil properties = new PropertiesUtil();
        def ecservletip = properties.readValue("ecservletip"); //获取配置文件ec接口IP
        def crmservletip = properties.readValue("crmservletip");//获取配置文件CRM接口IP
        def ecsecretkey = properties.readValue("ecsecretkey");//获取配置文件ec接口加密Key
        def receivebody = Util.getRequestBody(request, 'utf-8'); //获取报文
        log.debug("留言报文: " + receivebody);
        JSONObject obj = JSONObject.fromObject(receivebody);
        //obj.put("secretkey",ecsecretkey);
        def method = obj.get("method");
        def content = obj.get("content"); //获取content下内容
        def sqlrequest = "";
        def sqlresult = "";
        def rownum = 0;
        def requestinfo = "";
        def url = crmservletip + "/design";
        def charset = "utf-8";
        def timeout = 100000;
        def enableSSLflag = 0;
        /**
         def result=Util.doHttpPost(url,JSONObject.fromObject(obj).toString(),charset,timeout,enableSSLflag);
         if(result=='0'){
         return "{\"code\":\"e000002\",\"content\":\"\",\"msg\":\"\",\"rsp\":\"sign error!\",\"rspCode\":\"\",\"sub_msg\":\"签名错误!\"}"
         };
         */
        if (method == 'ec_message_addedit') {
            log.debug('=========================================' + method + "===================================");
            def customerguid = "";
            try {
                def usercode = Util.filterForObject(content.get("USER_CODE"));//获取会员编号
                if (usercode == '') {
                    return "{\"code\":\"e000001\",\"content\":\"\",\"msg\":\"\",\"rsp\":\"user_code is not null\",\"rspCode\":\"\",\"sub_msg\":\"系统用户编号不能为空！\"}"
                };
                sqlrequest = "select customer_guid from customer where customer_id='" + usercode + "'";
                sqlresult = eliteBean.chaxun_sql(sqlrequest, "dataSource");
                rownum = sqlresult.size;
                if (rownum == 0) {
                    requestinfo = "{\"flag\": \"ECCRM\",\"method\": \"userinfo\",\"type\": \"json\",\"charset\": \"utf-8\",\"ver\":1,\"timestamp\": \"\",\"content\": {\"USER_CODE\":\"" + usercode + "\"},\"sign\": \"\",\"secretkey\": \"" + ecsecretkey + "\"}";
                    url = crmservletip + "/ensign";
                    requestinfo = Util.doHttpPost(url, requestinfo, charset, timeout, enableSSLflag);
                    try {
                        requestinfo = Util.doHttpPost(ecservletip, requestinfo, charset, timeout, enableSSLflag);
                        requestinfo = new JsonSlurper().parseText(requestinfo); //解析json报文
                        requestinfo = requestinfo.content[0];
                        log.debug('requestinfo:' + requestinfo);
                        usercode = requestinfo.USER_CODE;
                        log.debug('usercode:' + usercode);
                    } catch (Exception e) {
                        log.error("", e);
                        return "{\"code\":\"e000003\",\"content\":\"\",\"msg\":\"\",\"rsp\":\"userinfo not exist\",\"rspCode\":\"\",\"sub_msg\":\"获取用户信息失败！\"}"
                    };
                    if (usercode == '') {
                        return "{\"code\":\"e000003\",\"content\":\"\",\"msg\":\"\",\"rsp\":\"userinfo not exist\",\"rspCode\":\"\",\"sub_msg\":\"获取用户信息失败！\"}"
                    };
                    customerguid = Util.getGuid();
                    sqlrequest = "insert into customer(customer_guid,customer_id,customername,mobile,customertype_id,idtype,customerid,stringfield12,stringfield14,stringfield15,createdby,createddate,relcodetable)values('" + customerguid + "','" + Util.filterForObject(requestinfo.USER_CODE) + "','" + Util.filterForObject(requestinfo.USER_NAME) + "','" + Util.filterForObject(requestinfo.MOBILETELE) + "','" + Util.filterForObject(requestinfo.USER_TYPE) + "','" + Util.filterForObject(requestinfo.PAPERTYPE) + "','" + Util.filterForObject(requestinfo.PAPERNUMBER) + "','" + Util.filterForObject(requestinfo.STATE) + "','" + Util.filterForObject(requestinfo.CFW_TYPE) + "','" + Util.filterForObject(requestinfo.REMARK) + "','SELITE',getdate(),'ecmessage')";
                    sqlresult = eliteBean.update(sqlrequest, "dataSource");
                } else {
                    customerguid = sqlresult[0].get("customer_guid");
                };
                try {
                    sqlrequest = "insert into tabcmessage_temp(customer_guid,message_id,id,user_code,user_name,user_idno,user_mobile,edit_reason,sex,pic_idno_z,pic_idno_f,pic_bank,bankcard,bankcard_new,bank_new,bank_province_new,bank_city_new,bankbook_new,pic_bank_new,pic_url,create_user_code,create_time,edit_user_code,edit_time,remark,state,type,agentno,address,contract_teacher,user_type_level,p_agentno,opening_date,agentno_level,licensing_status,cuser_name,flag,check_reason,return_reason,assign_to_user) values('" + customerguid + "','" + Util.filterForObject(content.get("MESSAGE_ID")) + "','" + Util.filterForObject(content.get("ID")) + "','" + Util.filterForObject(content.get("USER_CODE")) + "','" + Util.filterForObject(content.get("USER_NAME")) + "','" + Util.filterForObject(content.get("USER_IDNO")) + "','" + Util.filterForObject(content.get("USER_MOBILE")) + "','" + Util.filterForObject(content.get("EDIT_REASON")) + "','" + Util.filterForObject(content.get("SEX")) + "','" + Util.filterForObject(content.get("PIC_IDNO_Z")) + "','" + Util.filterForObject(content.get("PIC_IDNO_F")) + "','" + Util.filterForObject(content.get("PIC_BANK")) + "','" + Util.filterForObject(content.get("BANKCARD")) + "','" + Util.filterForObject(content.get("BANKCARD_NEW")) + "','" + Util.filterForObject(content.get("BANK_NEW")) + "','" + Util.filterForObject(content.get("BANK_PROVINCE_NEW")) + "','" + Util.filterForObject(content.get("BANK_CITY_NEW")) + "','" + Util.filterForObject(content.get("BANKBOOK_NEW")) + "','" + Util.filterForObject(content.get("PIC_BANK_NEW")) + "','" + Util.filterForObject(content.get("PIC_URL")) + "','" + Util.filterForObject(content.get("CREATE_USER")) + "','" + Util.filterForObject(content.get("CREATE_DATE")) + "','" + Util.filterForObject(content.get("EDIT_USER")) + "','" + Util.filterForObject(content.get("EDIT_DATE")) + "','" + Util.filterForObject(content.get("REMARK")) + "','" + Util.filterForObject(content.get("STATUS")) + "','" + Util.filterForObject(content.get("TYPE")) + "','" + Util.filterForObject(content.get("AGENTNO")) + "','" + Util.filterForObject(content.get("ADDRESS")) + "','" + Util.filterForObject(content.get("CONTRACT_TEACHER")) + "','" + Util.filterForObject(content.get("USER_TYPE_LEVEL")) + "','" + Util.filterForObject(content.get("P_AGENTNO")) + "','" + Util.filterForObject(content.get("OPENING_DATE")) + "','" + Util.filterForObject(content.get("AGENTNO_LEVEL")) + "','" + Util.filterForObject(content.get("LICENSING_STATUS")) + "','" + Util.filterForObject(content.get("CUSER_NAME")) + "','1','','" + Util.filterForObject(content.get("RETURN_RESON")) + "','')";
                    sqlresult = eliteBean.update(sqlrequest, "dataSource");
                    def procedure = "{call sp_ec_message_addedit(?,?)}";
                    def input = new String[1];
                    input[0] = Util.filterForObject(content.get("MESSAGE_ID"));
                    sqlresult = eliteBean.executeWithReturn(procedure, input, "dataSource");
                    if (sqlresult == '1') {
                        return "{\"code\":\"s001\",\"content\":\"\",\"msg\":\"\",\"rsp\":\"succ\",\"rspCode\":\"\",\"sub_msg\":\"留言新增/修改正常！\"}"
                    } else {
                        return "{\"code\":\"e000004\",\"content\":\"\",\"msg\":\"\",\"rsp\":\"insert or update data fail\",\"rspCode\":\"\",\"sub_msg\":\"留言新增/修改失败！\"}"
                    }
                } catch (Exception e) {
                    log.error("", e);
                    return "{\"code\":\"e000004\",\"content\":\"\",\"msg\":\"\",\"rsp\":\"insert or update data fail\",\"rspCode\":\"\",\"sub_msg\":\"留言新增/修改失败！\"}"
                }
            } catch (Exception e) {
                log.error("", e);
                return "{\"code\":\"e000005\",\"content\":\"\",\"msg\":\"\",\"rsp\":\"init interface fail\",\"rspCode\":\"\",\"sub_msg\":\"接口调用失败！\"}"
            }

        } else if (method == 'ec_message_status') {
            log.debug('=========================================' + method + "===================================");
            try {
                def m_type = content.get("TYPE");
                def m_remark;
                if (m_type.equals("2") || m_type == 2) {
                    m_remark = '指派人：' + content.get("EDIT_USERCODE") + ' 操作时间：' + content.get("EDIT_TIME") + ' ' + content.get("REMARK");
                } else if (m_type.equals("4") || m_type == 4 || m_type.equals("5") || m_type == 5) {
                    m_remark = '审批人：' + content.get("EDIT_USERCODE") + ' 审批时间：' + content.get("EDIT_TIME") + ' ' + content.get("REMARK");
                } else {
                    m_remark = content.get("REMARK");
                };
                def procedure = "{call sp_ec_message_status(?,?,?,?)}";
                def input = new String[3];
                input[0] = Util.filterForObject(content.get("MESSAGE_ID"));
                input[1] = Util.filterForObject(m_type);
                input[2] = Util.filterForObject(m_remark);
                sqlresult = eliteBean.executeWithReturn(procedure, input, "dataSource");
                if (sqlresult == '1') {
                    return "{\"code\":\"s001\",\"content\":\"\",\"msg\":\"\",\"rsp\":\"succ\",\"rspCode\":\"\",\"sub_msg\":\"留言状态更新成功！\"}"
                } else {
                    return "{\"code\":\"e000005\",\"content\":\"\",\"msg\":\"\",\"rsp\":\"init interface fail\",\"rspCode\":\"\",\"sub_msg\":\"接口调用失败！\"}"
                }
            } catch (Exception e) {
                log.error("", e);
                return "{\"code\":\"e000005\",\"content\":\"\",\"msg\":\"\",\"rsp\":\"init interface fail\",\"rspCode\":\"\",\"sub_msg\":\"接口调用失败！\"}"
            }
        }
    }
}